package com.xhtt.smart.card.server;

import com.alibaba.fastjson.JSON;
import com.xhtt.smart.card.common.msg.bean.MsgServerBean;
import com.xhtt.smart.card.server.init.NettyServerInitializer;
import com.xhtt.smart.card.server.util.NettySocketHolder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.net.InetSocketAddress;

/**
 * @author wangze
 * @date 2018-07-03 13:34.
 **/
@Component
public class NettyServer {

    private final static Logger LOGGER = LoggerFactory.getLogger(NettyServer.class);

    private EventLoopGroup acceptorGroup = new NioEventLoopGroup(1);
    private EventLoopGroup workerGroup = new NioEventLoopGroup();

    @Value("${netty.server.port}")
    private int nettyPort;


    /**
     * 启动 Netty
     *
     * @return
     * @throws InterruptedException
     */
    @PostConstruct
    public void start() throws InterruptedException {

        ServerBootstrap bootstrap = new ServerBootstrap()
                .group(acceptorGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .localAddress(new InetSocketAddress(nettyPort))
                //保持长连接
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(new NettyServerInitializer());

        ChannelFuture future = bootstrap.bind().sync();
        if (future.isSuccess()) {
            LOGGER.info("启动 Netty 成功");
        }
    }


    /**
     * 销毁
     */
    @PreDestroy
    public void destroy() {
        acceptorGroup.shutdownGracefully().syncUninterruptibly();
        workerGroup.shutdownGracefully().syncUninterruptibly();
        LOGGER.info("关闭 Netty 成功");
    }


    /**
     * 发送消息
     *
     * @param msg
     */
    public void sendMsg(MsgServerBean msg) {

        String id = msg.getDeviceType() + "-" + msg.getDeviceCode();

        NioSocketChannel socketChannel = NettySocketHolder.get(id);

        if (null == socketChannel) {
            throw new NullPointerException("没有[" + id + "]的socketChannel");
        }

        ChannelFuture future = socketChannel.writeAndFlush(msg);
        future.addListener((ChannelFutureListener) channelFuture ->
                LOGGER.info("服务端手动发消息成功={}", JSON.toJSONString(msg)));
    }

}
